<?php
namespace app\api\controller;
use app\common\controller\BaseApi;

/*健狗狗 api*/
class JGGApi extends  BaseApi
{
	//进出门禁
	const GetContractInfo="http://marspark.ifmtech.com/index.php/Home/FaceDoor/member";// 获取会员信息
	const CheckIn="http://marspark.ifmtech.com/index.php/Home/FaceDoor/innDoor";//进场
	const ConfirmCheckOut="http://marspark.ifmtech.com/index.php/Home/FaceDoor/outDoor"; //出场
	const OpenDoor="http://marspark.ifmtech.com/index.php/Home/FaceDoor/openDoor"; //开门回调
		
	protected $ClubId;//健身房id
	
	protected $shop_id;//店铺id
	
	/**
	 * 测试地址
	 * */
	 public function _initialize()
    {
    }
	/**
	 * 健狗狗调用
	 * 会员办卡
	 * http://smartgym.com/api/JGGApi/MemberCard
	 * */
	function MemberCard(){
		$this->_api_before_method();
		$data=['in_varifycation'=>1,"in_varifycation_type"=>2,'descs'=>"接口调用上传","owner_type"=>1,"is_original"=>1];
		$data['card_no']=input("card_no/s");
		$data['shop_id']=input("token/d");
		$data['member_id']=input("member_id");
		$data['contract_id']=input("contract_id");
		$data['name']=input("member_name");
		$data['mobile']=input("mobile");
		if(empty($data['mobile'])||strlen($data['mobile'])!=11){
		  return $this->jgg_ajax_error("手机号码格式有误");
		}
		if(empty($data['card_no'])||strlen($data['card_no'])!=10){
		  return $this->jgg_ajax_error("卡号格式有误（必须10位）");
		}
		$data['start_date']=input("start_date");
		$data['end_date']=input("end_date");
		$data['contract_status']=input("contract_status/d");
		$data['membership_type']=input("membership_type/d");
		$count=db("Interface")->where("shop_id=".$data['shop_id']." and card_no='".$data['card_no']."'")->count(1);
		if(empty($count)){
			db("Interface")->insert($data);
			$this->jgg_ajax_success();
		}else{
			$this->jgg_ajax_error("卡号已经存在");
		}
	}
	
	//http://smartgym.com/api/JGGApi/te
	function te(){
		var_dump($this->ConverUrlImage("http://cdn.smartfuns.com/upload/club/clubmember/images/2018/04/24/21520180424153659.jpg",54));die;
	}
	/**
	 * 提取url image 人脸特征
	 * http://smartgym.com/api/JGGApi/ConverUrlImage
	 * */
	function ConverUrlImage($url,$shop_id){
		$url=$this->saveimage($url,$shop_id);
		if(empty($url)){
			 return $this->jgg_ajax_error("无效的图片地址");
		}
		$face1=$this->_get_face_code($url);
		if(strlen($face1)<10000){
			return $this->jgg_ajax_error("图片无法提取到人脸模板:".$face1);
		}
		return $face1;
	}
	
	//保存图片并返回本地绝对路径,参数远程图片路径数组 
	function saveimage($url,$shop_id) {
    		if ($url == '') return false;
	        if(stripos($url,'http://')!== false or stripos($url,'ftp://')!== false){ //仅处理外部路径
	            $filename = substr($url, strripos($url, '/')); //图片名.后缀
	            $ext = substr($url, strripos($url, '.')); //图片后缀
	            if(!in_array($ext, array(".jpeg",".jpg",".png"))){
	            	return false;
	            }
	            $dir=ROOT_PATH . 'data' . DS . 'face'.DS.$shop_id;
	 			if(!file_exists($dir)){
					mkdir($dir);
				}
				$picdir=$dir."/".date("Ymd")."/"; //组合图片路径
	            if(!file_exists($picdir)){mkdir($picdir);}else{$t='生成文件夹失败 请检查权限！';}//缩略图所需文件夹不存在就生成下 
	            if(!file_exists($picdir)){$t='生成文件夹失败 请检查权限 生成路径='.$picdir;} 
	            $savepath = $picdir . strtotime("now") . $ext; //保存新图片路径
	            ob_start(); //开启缓冲
	            readfile($url); //读取图片
	            $img = ob_get_contents(); //保存到缓冲区
	            ob_end_clean(); //关闭缓冲
	            $fp2 = @fopen($savepath, "a"); //打开本地保存图片文件
	            fwrite($fp2, $img); //写入图片
	            fclose($fp2);
				return $savepath;
	        } else {
	        	return false;
	        }
	}
	
	/**
	 * 健狗狗调用
	 * 人脸3d 模型
	 * http://smartgym.com/api/JGGApi/Member3DImage
	 */ 
	function Member3DImage(){
		$this->_api_before_method();
		$shop_id=input("token");
		$card_no=input("card_no");
		if(empty($_FILES['file'])){
			$this->jgg_ajax_error("图片为空");
		}
		if($_FILES['file']['size']>210000){
			$this->jgg_ajax_error("图片不能大于200k");
		}
//		if(strpos($_FILES['file']['type'],"image")===false){
//			$this->jgg_ajax_error("图片格式有误".$_FILES['file']['type']);
//		}
	 	$file = request()->file('file');
	 	if(!empty($file)){
	 		$dir=ROOT_PATH . 'data' . DS . 'face'.DS.$shop_id;
	 		if(!file_exists($dir)){
				mkdir($dir);
			}
	 	 	$info = $file->move($dir);
			$headimage_url=$dir."/".date("Ymd")."/".$info->getFilename();
			$this->_save_face_code($headimage_url);
			$this->_model_down_record_save_update(array("card_no"=>$card_no,"shop_id"=>$shop_id,"type"=>2));
			return $this->jgg_ajax_success();
	 	 }else{
	 	 	return $this->jgg_ajax_error("文件为空");
	 	}
	}
	
	/**
	 * 模板是否新增或者修改---做记录
	 * */
	private function _model_down_record_save_update($data){
		$shop_id=$data['shop_id'];
		$card_no=$data['card_no'];
		$type=$data['type'];
		$model=db("ModelDownRecord")->where("card_no='$card_no' and shop_id=$shop_id and type=$type ")->field("id,card_no")->find();
		if(empty($model)){
			db("ModelDownRecord")->insert(array("card_no"=>$card_no,"shop_id"=>$shop_id,"type"=>$type,"is_down"=>0));
		}else{
			db("ModelDownRecord")->where("card_no='$card_no' and shop_id=$shop_id and type=$type")->update(array("is_down"=>0,"update_time"=>date("Y-m-d H:i:s")));
		}
	}
	/*保存人脸模板*/
	function _save_face_code($icon1){
		$card_no=input("card_no");
		$shop_id=input("token");
		$count=db("Interface")->where("shop_id=$shop_id  and card_no='$card_no'")->count(1);
		if(empty($count)){
			return $this->jgg_ajax_error("卡号不存在");
		}
		$face1=$this->_get_face_code($icon1);
		if(strlen($face1)<10000){
			return $this->jgg_ajax_error("人脸模板错误:".$face1);
		}
		$count=db("FaceCode")->where("card_no='$card_no' and shop_id=$shop_id")->count(1);
		if(empty($count)){
			db("FaceCode")->insert(array("shop_id"=>$shop_id,"card_no"=>$card_no,"face1"=>$face1,"icon1"=>str_replace(ROOT_PATH, "/", $icon1)));
		}else{
			db("FaceCode")->where("card_no='$card_no' and shop_id=$shop_id")->update(array("face1"=>$face1,"icon1"=>str_replace(ROOT_PATH, "/", $icon1)));
		}
		
	}
	/**调用python 获取人脸模板*/
	function _get_face_code($icon){
		return  str_replace(array("\r\n", "\r", "\n"),"",shell_exec("python /etc/nginx/www/arcface/python/c.py $icon"));
	}
	/*api 调用前 检测*/
	function _api_before_method(){
		if(!request()->isPost()){
			$this->jgg_ajax_error("非法访问");
		}
		if(empty(input("token/d"))){
			$this->jgg_ajax_error("参数错误1");
		}
		if(empty(input("card_no"))){
			$this->jgg_ajax_error("参数错误2");
		}
		if(empty(input("sign"))){
			$this->jgg_ajax_error("参数错误3");
		}
		if(empty(input("time/d"))){
			$this->jgg_ajax_error("参数错误4");
		}
		if(input("debug")==1){
		}else{
			if((input('time')+300)<time()||(input('time')-300)>time()){//接口调用时间操过5分钟
				return $this->jgg_ajax_error("链接已经过期");
				}	
			if($this->_get_sign(input('card_no'),input('time'),input('token'))!=input('sign')){
				$this->jgg_ajax_error("签名错误");
			}	
		}
		
	}

	function jgg_ajax_success($data=""){
		header('Content-Type:application/json; charset=utf-8');
    	exit(json_encode(array('flag'=>TRUE,"msg"=>"成功","data"=>$data),JSON_UNESCAPED_UNICODE));die;
	}
	function jgg_ajax_error($msg=""){
		header('Content-Type:application/json; charset=utf-8');
    	exit(json_encode(array('flag'=>FALSE,"msg"=>$msg,"data"=>""),JSON_UNESCAPED_UNICODE));die;
	}
	function _get_sign($card_no,$time,$token){
		return md5($card_no.$time.$token);
	}
	function test(){
		$icon="/etc/nginx/www/smartgymdemo/data/face/58/20180323/08de7259625d43ae44f3fc25857681d5.jpg";
		//$icon="/etc/nginx/www/arcface/python/a.jpg";
		$result=$this->_get_face_code($icon);
		var_dump($result);
	}
	////////////////////////////////////////////////////////////////////////////////////////////////
	/**
	 * 方法前操作获取店铺信息
	 */
	function before_method($shop_id){
		if(empty($shop_id)){
			$this->ajax_error('','',"店铺id 为空");
		}else{
			$this->shop_id=$shop_id;
		}
		$config=cache("ExtraConfig_".$this->shop_id);
    	if(empty($config)){
			 $config=db("Shop")->where("id=".$this->shop_id)->value("extra_config");
			 if(empty($config)){
			 	$this->ajax_error('','',"请配置健狗狗代码");
			}
			 $config=json_decode($config,TRUE);
			 cache("ExtraConfig_".$this->shop_id,$config);
    	} 
		$this->ClubId=$config['ClubId'];
	}
	/**
	 * 获取合同号
	 * @param $card_no
	 * @return $data
	 * [
	 *	    {
	 *		        "ContractID": "06162ef0-7022-433e-80bd-7d9d44dc113c",
	 *		        "MemberID": "5c5313c8-aa5b-493a-8664-88e89b19a6ca",
	 *		        "MemberName": "ERCC",
	 *		        "Mobile": "18523020102",
	 *		        "CardNo": "2238082314",
	 *		        "StartDate": "2017-10-19",
	 *		        "EndDate": "2018-10-28",
	 *		        "ContractStatus": 1,
	 *		        "MembershipType": 2,
	 *		        "MembershipTypeName": "骞存湀鍗�",
	 *		        "SurplusNum": "0",
	 *		        "MemberUrl": ""
	 *		    }
	 *		]
	 * http://smartgym.com/api/JGGApi/GetContractInfo/card_no/1/shop_id/58
	 */
	function GetContractInfo($card_no,$shop_id){
		$this->before_method($shop_id);
		$result=http_get(self::GetContractInfo,['ClubID'=>1,"CardNo"=>$card_no]);
		if($result['flag']){
			$json= json_decode($result['data'],TRUE);
			if(empty($json)){
				return template_error('配置错误或者同步数据无效(健狗狗)');
			}else{
				if(empty($json['CardNo'])){
					return template_error("无效的卡号(健狗狗)");
				}else{
					return template_success('成功(健狗狗)',$json);
				}
			}			
		}else{
			return template_error($result['msg'].".");
		}
	}
	/**
	 * 入场操作
	 * @param $card_no
	 * http://smartgym.com/api/JGGApi/CheckIn/shop_id/58/card_no/8888888888
	 */
	function CheckIn($card_no,$shop_id){
		$this->before_method($shop_id);
		$result=http_get(self::CheckIn,["ClubID"=>$this->ClubId,"CardNo"=>$card_no]);
		if($result['flag']){
			$json= json_decode($result['data'],TRUE);
			if(empty($json)){
				return template_error("配置错误或者卡号错误(健狗狗)");
			}else{
				if($json['Status']!=1){//失败
					return template_error("失败(健狗狗)".$json['Status']);
				}else{//成功
					return template_success("成功",$json['Status'].".");
				}
				
			}			
		}else{
			return template_error($result['msg'].".");
		}
	}
	/**
	 * 出场操作
	 * @param $card_no
	 * http://smartgym.com/api/JGGApi/ConfirmCheckOut/shop_id/58/card_no/1
	 */
	function ConfirmCheckOut($card_no,$shop_id){
		$card_no="1";
		$this->before_method($shop_id);
		$result=http_get(self::ConfirmCheckOut,["ClubID"=>$this->ClubId,"CardNo"=>$card_no]);
		if($result['flag']){
			$json= json_decode($result['data'],TRUE);
			if(empty($json)){
				return template_error("配置错误或者卡号错误(健狗狗)");
			}else{
				if($json['Status']!=1){
					return template_success("成功(健狗狗)",$json);
				}else{
					return template_error($json['Status'].".");
				}
			}			
		}else{
			return template_error($result['msg'].".");
		}
	}
	function anke_error($code){
          $error=[
            '1'=>"成功(健狗狗)",
            '-1'=>"系统错误(健狗狗)",
            '-2'=>"参数错误(健狗狗)",
            '-3'=>"此卡为外店卡，不能在本地通用(健狗狗)",
            '-4'=>"剩余次数为0(健狗狗)",
            '-5'=>"已超过该会员携带的人数（健狗狗）",
            '-6'=>"主卡不再场,副卡无法入场（健狗狗）",
            '-7'=>'高峰时段卡，目前禁止入场(健狗狗)',
            '-8'=>'当日利用次数已完,无法入场(健狗狗)',
            '-9'=>'本周利用次数已完，无法入场（健狗狗）',
            '-10'=>'本周利用次数已完，无法入场（健狗狗）',
            '-11'=>'入场类商品不存在，无法入场（健狗狗）',
            '-12'=>'储值卡余额不足，无法入场',
          ];
		if(in_array($code,array_keys($error))){
			return $error[$code];
		}else{
			return "卡号不存在 或者未知的错误类型(健狗狗)";
		}		
	}
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	/**
	 * 建构狗开门回调
	 * smartgym.com/api/JGGApi/jgg_callback
	 * */
	function jgg_callback(){
		$shop_id=input("shop_id/d");
		$card_no=input("card_no/s");
		if(empty($card_no)||empty($shop_id)){
			$this->jgg_ajax_error("参数错误");	
		}else{
			$this->before_method($shop_id);
			$result=http_get(self::OpenDoor,["ClubID"=>$this->ClubId,"CardNo"=>$card_no]);
			db("CallbackLog")->insert(array(
					"parameters"=>json_encode(["ClubID"=>$this->ClubId,"CardNo"=>$card_no],JSON_UNESCAPED_UNICODE),
					"url"=>self::OpenDoor,
					"method"=>"get",
					"results"=>json_encode($result,JSON_UNESCAPED_UNICODE),
					"shop_id"=>$shop_id,
			));
			$this->jgg_ajax_success(json_encode($result,JSON_UNESCAPED_UNICODE));
		}
	}
}
